package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ForumDao;
import com.example.simpleforum.dao.PostDao;
import com.example.simpleforum.model.Forum;
import com.example.simpleforum.model.Post;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 帖子列表Servlet
 */
public class PostListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PostDao postDao = new PostDao();
        List<Post> posts;
        
        // 获取板块ID参数
        String forumIdParam = request.getParameter("forumId");
        
        if (forumIdParam != null && !forumIdParam.isEmpty()) {
            // 查询指定板块的帖子
            int forumId = Integer.parseInt(forumIdParam);
            posts = postDao.findPostsByForumId(forumId);
            request.setAttribute("forumId", forumId);
        } else {
            // 查询所有帖子
            posts = postDao.findAllPosts();
        }
        
        // 获取所有板块
        ForumDao forumDao = new ForumDao();
        List<Forum> forums = forumDao.findAll();
        
        // 创建板块名称映射
        for (Forum forum : forums) {
            request.setAttribute("forumName_" + forum.getId(), forum.getName());
        }
        
        // 将数据存入请求属性
        request.setAttribute("posts", posts);
        request.setAttribute("forums", forums);
        
        // 转发到帖子列表页面
        request.getRequestDispatcher("/postList.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // POST请求也执行相同操作
        doGet(request, response);
    }
}